﻿using System;
using System.Collections.Generic;
using System.Linq;
using oModbus.Utility;

namespace oModbus.Message
{
    public class ReadInputRegisterResponse : AbstractModbusMessage
    {
        public ReadInputRegisterResponse(byte slaveAddress, List<byte> inputState) : base(slaveAddress, FunctionCode.ReadInputRegister)
        {
            InputState =inputState;
        }

        public ReadInputRegisterResponse(byte[] messageBytes) : base(messageBytes)
        {
        }



        /// <summary>
        /// 内容字节数 1个字节	N*
        /// </summary>
        public byte ByteSize { get; protected set; }

        private List<byte> _inputState;
        /// <summary>
        /// 线圈状态  n＝N或N+1
        /// </summary>
        public List<byte> InputState
        {
            get { return _inputState; }
            set
            {
                _inputState = value;
                ByteSize = (byte)(_inputState.Count);
            }
        }

        protected override void Packing()
        {
            base.Packing();

            MessageData.Add(ByteSize);
            MessageData.AddRange(InputState);
            Crc = MessageData.ToArray().CalculateCrc();
        }

        public override bool Analysis(byte[] messageBytes)
        {
            if (messageBytes.Length >= 5)
            {

                MessageData = messageBytes.ToList();
                FunctionCode = (FunctionCode)Convert.ToInt32(messageBytes[1]);
                ByteSize = messageBytes[2];
                var temp = new List<byte>();
                for (int i = 3; i < messageBytes.Length - 2; i++)
                {
                    temp.Add(messageBytes[i]);
                }
                _inputState = temp;
                Crc = new List<byte>()
                {
                    messageBytes[messageBytes.Length - 2],
                    messageBytes[messageBytes.Length - 1]
                }.ToArray();
                return true;
            }
            return false;
        }
    }
}
